from point import Point

#Basic implementation for a line
class Line(object):
    def __init__(self, p1, p2):
        assert isinstance(p1, Point)
        assert isinstance(p2, Point)
        self._p1, self._p2 = p1, p2
        self._m = None
        self._b = None
        if (p1.x != p2.x):
            self._m = (p1.y - p2.y) / (p1.x - p2.x)
            self._b = p1.y - self._m * p1.x
    @staticmethod
    def new_line(m, b):
        return Line(Point(1, b + m * 1), Point(0, b))
    @staticmethod
    def new_x_line(x):
        return Line(Point(x, 0), Point(x, 1))
    def __str__(self):
        return "<Line [%s, %s]>" % (str(self._p1), str(self._p2))
    def __repr__(self):
        return "<Line [%s, %s]>" % (str(self._p1), str(self._p2))
    @property
    def p1(self):
        return self._p1
    @property
    def p2(self):
        return self._p2
    @property
    def m(self):
        return self._m
    @property
    def b(self):
        return self._b
    def __eq__(self, other):
        assert isinstance(other, Line)
        return (self._p1 == other._p1) and (self._p2 == other._p2)
    def intersect(self, other):
        assert isinstance(other, Line)
        assert self._m != other._m
        if (self._m == None):
            return Point(self.p1._x, other._m * self.p1._x + other._b)
        elif (other._m == None):
            return Point(other.p1._x, self._m * other.p1._x + self._b)
        else:
            tmp_x = (other._b - self._b) / (self._m - other._m)
            return Point(tmp_x, self._m * tmp_x + self._b)
    def __add__(self, other):
        assert isinstance(other, Line)
        return Line(self.p1 + other.p1, self.p2 + other.p2)
    def __sub__(self, other):
        assert isinstance(other, Line)
        return Line(self.p1 - other.p1, self.p2 - other.p2)
